package com.example.stujava.module.socked.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class Sender {
    public static void main(String[] args) {
        String text = "A sentence from the sender";
        String toIP = "127.0.0.1";
        int toPort = 10000; //10000~65535
        byte[] bytes = text.getBytes();

        sendUDP(toIP, toPort, bytes, 0, bytes.length);
    }

    private static void sendUDP(String toIP, int toPort, byte[] bytes, int offSet, int length) {
        DatagramSocket socked = null;
        try {
            socked = new DatagramSocket();
            //把数据打成包裹
            DatagramPacket packet = new DatagramPacket(bytes, offSet, length, InetAddress.getByName(toIP), toPort);
            //发送
            socked.send(packet);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //结束
            if (socked != null) {
                socked.close();
            }
        }
    }
}
